package com.fjwt.gz.task.log;

import com.fjwt.gz.db.entity.SysScheduledLogEntity;
import com.fjwt.gz.service.impl.SysScheduledLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Date;

/**
 * 定时任务日志服务
 * @author mei
 */
@Service
public class TaskLogService {

    @Autowired
    private SysScheduledLogService sysScheduledLogService;

    /**
     * 任务执行中
     */
    private static final String PROCESSING = "PROCESSING";
    /**
     * 任务成功
     */
    private static final String SUCCESS = "SUCCESS";
    /**
     * 任务失败
     */
    private static final String FAILED = "FAILED";

    /**
     * 记录任务开始
     * 使用REQUIRES_NEW确保日志事务独立
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public long logTaskStart(String taskName, String methodName, String cron) {
        SysScheduledLogEntity scheduledLog = new SysScheduledLogEntity();
        scheduledLog.setScheduledName(taskName);
        scheduledLog.setMethodName(methodName);
        scheduledLog.setCronExpression(cron);

        scheduledLog.setStatus(PROCESSING);

        // 保持原有事务控制
        sysScheduledLogService.save(scheduledLog);
        return scheduledLog.getSysScheduledLogId();
    }
    
    /**
     * 记录任务成功
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void logTaskSuccess(long logId) {
        updateTaskStatus(logId, SUCCESS, null);
    }
    
    /**
     * 记录任务失败
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void logTaskFailure(long logId, Throwable throwable) {
        String errorMsg = throwable.getMessage();
        if (errorMsg == null) {
            errorMsg = throwable.getClass().getName();
        }
        updateTaskStatus(logId, FAILED, errorMsg);
    }

    private void updateTaskStatus(long logId, String status, String error) {
        SysScheduledLogEntity scheduledLog = new SysScheduledLogEntity();
        scheduledLog.setSysScheduledLogId(logId)
                .setStatus(status)
                .setCompletedTime(new Date());

        if (error != null) {
            // 确保错误信息不超过1024字符并记录完整错误信息
            String truncatedError = error.length() > 1024 ? error.substring(0, 1024) : error;
            scheduledLog.setErrorMsg(truncatedError);
        }
        sysScheduledLogService.updateById(scheduledLog);
    }
}